import IP2Region from "ip2region";
import path from "path";
import { fileURLToPath } from "url";
import { cleanIp, validateIp } from "../utils/ip.validator.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建 IP2Region 实例
const searcher = new IP2Region();

const getIpInfo = async (ip) => {
  try {
    // 清理和验证IP地址
    const cleanIpAddress = cleanIp(ip);
    
    if (!cleanIpAddress) {
      throw new Error("无法获取有效的IP地址");
    }

    if (!validateIp(cleanIpAddress)) {
      throw new Error(`无效的IP地址格式: ${cleanIpAddress}`);
    }

    const result = await searcher.search(cleanIpAddress);

    if (!result) {
      throw new Error("未找到IP地址信息");
    }

    return {
      ip: cleanIpAddress,
      country: result.country || "未知",
      region: result.region || "未知",
      province: result.province || "未知",
      city: result.city || "未知",
      isp: result.isp || "未知",
    };
  } catch (error) {
    console.error("IP查询错误:", error);
    throw new Error("IP地址查询失败: " + error.message);
  }
};

export default getIpInfo;
